package com.shushan.shushanbao.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.Constants;
import com.shushan.home.OpenSectVipActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.OpenVIPsuccessActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.service.DialRTAService;
import com.shushan.service.ForegroundRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.shushanbao.wxapi.bean.OrderBean;
import com.shushan.ui.WaitDialog;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToastUtils;
import com.shushan.util.UmengEventUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;


public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
	
	private static final String TAG = "WXPayEntryActivity";

	private WaitDialog mWaitDialog;

    private IWXAPI api;
	private final static int DELAY_TIMES = 1000*3;
	private int loopCount = 0;
	private BabyApplication babyApplication = BabyApplication.getInstance();
	public static int type = 1;//支付类型 1:全类vip购买 2:分类vip购买 3:提分计划购买 4:广告活动购买 5:10元体验7天

	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what){
				case 0:
					loopCount++;
					querryOrder();
					break;
			}
		}
	};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG,"onCreate()");

    	api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);

		mWaitDialog = new WaitDialog(this, R.style.Dialog_Translucent_Background);
    }

	@Override
	protected void onDestroy() {
		super.onDestroy();

		Log.i(TAG,"onDestroy()");
		if(mWaitDialog != null  && !isFinishing()){
			mWaitDialog.dismiss();
			mWaitDialog = null;
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		Log.i(TAG,"onNewIntent()");

		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {

		Log.i(TAG,"onReq()");
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.i(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			if(resp.errCode == BaseResp.ErrCode.ERR_OK){
				showWaitDialog();
				querryOrder();
			}else if(resp.errCode == BaseResp.ErrCode.ERR_COMM){//支付失败
				onFaildEvent(type,"ERR_COMM");
				ToastUtils.showToast(this,"支付失败");

				finish();
			}else if(resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL){//取消支付
				onFaildEvent(type,"ERR_USER_CANCEL");
				ToastUtils.showToast(this,"您已经取消支付");

				finish();
			}

			boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
			if(isChildControl){
				Intent intent1 = new Intent(this,DialRTAService.class);
				stopService(intent1);
			}

		}else {
			finish();
		}

	}

	private void querryOrder() {
    	if(loopCount >= 3){
			dismissWaitDialog();

			ToastUtils.showToast(this,"支付存在延迟，稍后会处理");
			onFaildEvent(type,"unknow");

			finish();
    		return;
		}

		String outTradeNo = SharedPreferencesUtils.getStringDate(Constants.OUT_TRADE_NO_SHAREPREFERS_KEY);
    	if(TextUtils.isEmpty(outTradeNo)){

			dismissWaitDialog();

			ToastUtils.showToast(this,"订单号为空");
			onFaildEvent(type,"订单号为空");

    		finish();
    		return;
		}

		UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.QUERRY_ORDER);
		urlParse.putValue("out_trade_no",outTradeNo);

		NetHelper.create()
				.url(urlParse.toStringOnlyHeader())
				.param(urlParse.toStringOnlyParam())
				.request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<OrderBean>() {

					@Override
					protected void onSuccess(OrderBean orderBean) {
						HashMap<String,String> map = new HashMap<String,String>();
						map.put("account",orderBean.phone);
						map.put("money",orderBean.money+"");
						onSuccessEvent(type,map);
						dismissWaitDialog();

						ToastUtils.showToast(WXPayEntryActivity.this,"支付成功");

						ActivityStackManager.getActivityStackManager().popTopActivity();

						finish();

					}

					@Override
					protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
						mHandler.sendEmptyMessageDelayed(0,DELAY_TIMES);
					}
				});
	}

	/**
	 * 显示加载动画
	 *
	 */
	protected void showWaitDialog() {

		if(mWaitDialog != null && !mWaitDialog.isShowing() && !isFinishing()){
			mWaitDialog.show();
		}

	}

	/**
	 * 关闭加载动画
	 *
	 */
	protected void dismissWaitDialog() {
		if (isFinishing()){
			return;
		}

		if(mWaitDialog != null && mWaitDialog.isShowing()){
			mWaitDialog.dismiss();
		}
	}

	public void onFaildEvent(int type,String label){
		//支付类型 1:全类vip购买 2:分类vip购买 3:提分计划购买 4:广告活动购买 5:10元体验7天
		switch (type){
			case 1:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_supper_faild_id",label);
				break;
			case 2:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_sect_faild_id",label);
				break;
			case 3:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_extract_faild_id",label);
				break;
			case 4:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_advert_faild_id",label);
				break;
			case 5:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_taste_faild_id",label);
				break;
			default:
				break;
		}
	}

	public void onSuccessEvent(int type,HashMap<String,String> map){
		if(map == null){
			return;
		}
		//支付类型 1:全类vip购买 2:分类vip购买 3:提分计划购买 4:广告活动购买 5:10元体验7天
		switch (type){
			case 1:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_supper_success_id",map);
				break;
			case 2:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_sect_success_id",map);
				break;
			case 3:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_extract_success_id",map);
				break;
			case 4:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_advert_success_id",map);
				break;
			case 5:
				UmengEventUtil.onEvent(babyApplication,"open_vip_wechat_taste_success_id",map);
				break;
			default:
				break;
		}
	}
}